
layui.use(['form', 'layedit', 'laydate',"table",'upload'], function() {
    var $ = layui.jquery
        , upload = layui.upload;
    var table = layui.table;
    var form = layui.form
        , layer = layui.layer
        , layedit = layui.layedit
        , laydate = layui.laydate;
    laydate.render({
        elem: '#searchStartTime'
        ,type: 'datetime'

    });
    laydate.render({
        elem: '#searchEndTime'
        ,type: 'datetime'
    });

    //自定义验证规则
    form.verify({

        search: function (value) {
            if(!new RegExp("^[+]{0,1}(\\d+)$").test(value)&&value != null&&value != ""){
                return 'ID为正整数';
            }
            if (value >999999){
                return 'ID数字过大';

            }
        },
        content:function (value) {

            if(value.length>100){
                return 'ID长度不超过100个字符';
            }
        }

    });
    var publisher=$('#videoPublisher').val()
    //多文件列
    var demoListView = $('#demoList')
        ,uploadListIns = upload.render({
        elem: '#testList'
        ,url: '/videoController/uploadVideo'
        ,accept: 'video'
        ,multiple: true
        ,auto: false
        ,bindAction: '#testListAction'
        ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            var publisher= $('#videoPublisher').val()


            this.data={'publisher':publisher};
            if  (isNull(publisher)){
                layer.alert('请填写视频所属用户ID', {icon: 5});
            }
            layer.load(); //上传loading
        }

        ,choose: function(obj){
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function(index, file, result){
                var tr = $(['<tr id="upload-'+ index +'">'
                    ,'<td>'+ file.name +'</td>'
                    ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                    ,'<td>等待上传</td>'
                    ,'<td>'
                    ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    ,'</td>'
                    ,'</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function(){
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function(){
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                demoListView.append(tr);
            });
        }
        ,done: function(data,index, upload){
            layer.closeAll('loading'); //关闭loading
            if(data.code == 0 && data.vidoeId != null) { //上传成功
                // var request = window.indexedDB.open('db', 1);
                //
                // request.onsuccess = function (event) {
                //     var db = event.target.result;
                //
                //     var transaction = db.transaction(['video'], 'readwrite');
                //
                //     var objectStore = transaction.objectStore('video');
                //
                //     objectStore.add({name: data.name, videoId: data.vidoeId});
                //     request.onsuccess = function (event) {
                //         // 对 request.result 做些操作！
                //         console.log('成功插入');
                //     };
                //     request.onerror = function (event) {
                //         console.log('插入失败');
                //     };
                // }
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }

        }
        ,error: function(index, upload){
            layer.closeAll('loading'); //关闭loading
            var tr = demoListView.find('tr#upload-'+ index)
                ,tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            layer.closeAll('loading'); //关闭loading
        }
        ,allDone: function(obj){ //当文件全部被提交后，才触发
            layer.closeAll('loading'); //关闭loading
            console.log(obj.total); //得到总文件数
            console.log(obj.successful); //请求成功的文件数
            console.log(obj.aborted); //请求失败的文件数
            layer.alert('上传成功', {icon: 1}, function(index){
                layer.closeAll("page");
                layer.close(index);
             location.href=  location.href
            });
        }
    });

    //上传excel
    upload.render({
        elem: '#addVideoAndInfo'
        ,url: '/videoController/uploadVideoInfo'
        ,accept: 'file'
        ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            var array = new Array();
            // var request = window.indexedDB.open('db', 1);
            var transaction = db.transaction(['video'], 'readwrite');
            var objectStore = transaction.objectStore('video');
            var cursorRequest = objectStore.openCursor();
            cursorRequest.onsuccess=function (event) {
                var cursor = event.target.result;
                if (cursor){

                    var  info = cursor.value.name+"-"+cursor.value.videoId
                    array.push(info)
                }
            }
            array.join(',')
            console.log(array)
            this.data={'vidoeInfo':array};

            layer.load(); //上传loading
            request.onsuccess = function (event) {
             console.log("掺杂的")

            }


        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading

        }
        ,error: function(index, upload){
            layer.closeAll('loading'); //关闭loading
        }
    });
    //监听工具条
    table.on('tool(demo)', function(obj){
        var data = obj.data;
        if(obj.event === 'openVideo'){
            if (data.url != null && data.url != "" && data.url != undefined){

                var myVideo = videojs('myVideo',{

                    bigPlayButton : false,

                    textTrackDisplay : false,

                    posterImage: false,

                    errorDisplay : false,

                })
                    var  vdoSrc = data.url
                var faceUrl =data.videoFaceImage
                    if(/\.m3u8$/.test(vdoSrc)){//判断视频源是否是m3u8的格式

                        myVideo.src({

                            src: vdoSrc,

                            type: 'application/x-mpegURL'//在重新添加视频源的时候需要给新的type的值

                        })
                        myVideo.poster(faceUrl)

                    }else{
                        myVideo.poster(faceUrl)
                        myVideo.src({

                            src: vdoSrc,

                            type: 'video/mp4'//在重新添加视频源的时候需要给新的type的值

                        })

                    }

                    myVideo.load();

                    myVideo.play();



                layer.open({
                    type: 1,
                    title: false,
                    area: ['630px', '360px'],
                    shade: 0.8,
                    closeBtn: 0,
                    shadeClose: true,
                    content:$("#openVideo")
                });
            }else{
                layer.alert('此视频不可播放', {icon: 5});
            }
        } else if(obj.event === 'del'){
            layer.confirm('确定删除吗?', function(index){
                $.ajax({
                    url:"/videoController/delById",
                    type:"POST",
                    data:{id:data.id},
                    dataType:"json",
                    success:function(data,status,xhr){
                        if (xhr.code == -1){
                            top.location.href="/pageController/login"

                        }
                        if(xhr.status == 204){
                            layer.alert('删除成功', {icon: 1}, function(index){
                                layer.closeAll("page");
                                layer.close(index);
                                var curr = sessionStorage.getItem("curr");
                                table.reload('testReload',{page:{curr:curr}});
                            });
                        }else if(xhr.status == 500){
                            layer.alert('内部服务器错误', {icon: 5});
                        }
                    }
                })
                layer.close(index);

            });
        } else if(obj.event === 'edit'){
            $('#videoId').val(data.videoId)

            if (data.tags != null && data.tags != ""){
                $('#addTags').importTags(data.tags)
            }else {
                $('#addTags').importTags("")
            }

            var  width=($(window).width()*0.4);
            var height=($(window).height()*0.5);
            layer.open({
                type: 1,
                closeBtn: 0,
                area: [width + 'px', height + 'px'],//大小
                content: $("#addUpdate"),
                skin: "layui-layer-molv",
                title:  "视频标签编辑"
                ,btnAlign: 'c'
                ,btn: ['保存', '取消']
                ,yes: function(index, layero){
                    layero.find('form').find('button[lay-submit]').click();
                    return false
                }
                ,btn2: function(){
                    layer.closeAll();
                }
            })
        }else if (obj.event === 'updateContent'){
            $('#momentId').val(data.id)
            $('#publisher').val(data.publisher)
            if (data.contentText != null && data.contentText != ""){
                $("#contentText").val(data.contentText);
            }else{
                $("#contentText").val("")
            }
            var  width=($(window).width()*0.5);
            var height=($(window).height()*0.5);
            layer.open({
                type: 1,
                closeBtn: 0,
                area: [width + 'px', height + 'px'],//大小
                content: $("#contentUpdate"),
                skin: "layui-layer-molv",
                title:  "视频标题编辑"
                ,btnAlign: 'c'
                ,btn: ['保存', '取消']
                ,yes: function(index, layero){
                    layero.find('form').find('button[lay-submit]').click();
                    return false
                }
                ,btn2: function(){
                    layer.closeAll();
                }
            })


        }
    });


    //提交标签更新
    form.on('submit(subTag)', function(data){
            var tags=$("#addTags").val();
        $.ajax({
            url:"/videoController/updateTag",
            type:"POST",
            data:data.field,
            // dataType:"json",
            success:function(data,status,xhr){

                if(xhr.status == 201){
                    layer.alert('编辑成功', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        // location.href=location.href;
                       var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});
                    });
                }else  if(xhr.status == 500){
                    layer.alert('服务器内部错误', {icon: 5});
                }


            },
            error:function (data,status,xhr) {

                layer.alert('系统出错!', {icon: 5},function () {
                    layer.closeAll();
                });

            }
        })
        return false;
    });

    //提交标题更新
    form.on('submit(subContent)', function(data){
        var contentText =$('#contentText').val();
       var length= contentText.trim().length;
        if (length >60){
            layer.alert('视频标题不超过60个字符!', {icon: 5});
            return false;
        }
        $.ajax({
            url:"/videoController/updateContent",
            type:"POST",
            data:data.field,
            success:function(data,status,xhr){

                if(xhr.status == 204){
                    layer.alert('编辑成功', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});                    });
                }else  if(xhr.status == 500){
                    layer.alert('服务器内部错误', {icon: 5});
                }


            },
            error:function (data,status,xhr) {

                layer.alert('系统出错!', {icon: 5},function () {
                    layer.closeAll();
                });

            }
        })
        return false;
    });

    //提交视频合成
    form.on('submit(subSynthesisVideo)', function(data){
        var  description= data.field.contentText
        if (description.length >100){
            layer.alert('视频标题在100个字符以内', {icon: 5});
            return false;
        }
        //tail处理值
        if(data.field.tailSwitch == "on") {
            data.field.tailSwitch = "1";
        } else {
            data.field.tailSwitch = "0";
        }
        //获取视频id数组
        var  json =$('#gridDemo').find('img');
        var array = new Array();
        $.each(json,function (i,n) {
          var id = $(this).attr("data-id");
            array.push(id);
        })
        array.join(",");
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        $.ajax({
            url:"/videoController/synthesisVideo?videoInfos="+array,
            type:"POST",
            data:data.field,
            success:function(data,status,xhr){
                layer.close(loading);
                if(xhr.status == 201){
                    layer.alert('合成视频成功,请等待视频剪辑完成后播放!', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});                    });
                }else if (xhr.status == 204){
                    layer.alert('合成视频失败', {icon: 5});
                }
                else  if(xhr.status == 500){
                    layer.alert('服务器内部错误', {icon: 5});
                }


            },
            error:function (data,status,xhr) {
                layer.close(loading);
                layer.alert('系统出错!', {icon: 5},function () {
                    layer.closeAll();
                });

            }
        })
        return false;
    });


    //提交迁移视频
    form.on('submit(subTransfer)', function(data){
       var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
       var clubid= $("#searchClub").val();
        $.ajax({
            url:"/sjs/transferVideo?",
            type:"POST",
            data:data.field,
            success:function(data,status,xhr){
                layer.close(loading);
                if(xhr.status == 201){
                    layer.alert('迁移成功', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});
                    });
                }else  if(xhr.status == 500){
                    layer.alert('服务器内部错误', {icon: 5});
                }else if (xhr.status == 204){
                    layer.alert('该俱乐部此时间段无视频', {icon: 5});

                }

            },
            error:function (data,status,xhr) {

                layer.alert('系统出错!', {icon: 5});
            }
        })
        return false;
    });

    //提交新增视频
    form.on('submit(subAddVideo)', function(data){
        var vid= $('#newVideoId').val()
        if  (vid == null || vid ==""){
            layer.alert('请上传视频!', {icon: 5});
            return false;
        }

        $.ajax({
            url:"/videoController/addVideo",
            type:"POST",
            data:data.field,
            success:function(data,status,xhr){
                if(xhr.status == 201){
                    layer.alert('新增视频成功', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});
                    });
                }else  if(xhr.status == 500){
                    layer.alert('服务器内部错误', {icon: 5});
                }else if (xhr.status == 400){
                    layer.alert('参数错误', {icon: 5});

                }else if (xhr.status == 204){
                    layer.alert('用户ID不存在,请重新填写', {icon: 5});
                }

            },
            error:function (data,status,xhr) {

                layer.alert('系统出错!', {icon: 5});
            }
        })
        return false;
    });
    //开关监控
    form.on('checkbox(tailSwitch)', function(data){
        if(data.elem.checked){
            $('#tail').show();

            $("input[name='videoTail']").val("8e9c978ee4064f6ab017b3532eeecdb3")
        }else{
            $('#tail').hide();
            $("input[name='videoTail']").val("")
        }
    });




    $(function () {
        //片尾开关
        if($('#tailSwitch').is(':checked')){
            $('#tail').show();
        }else if (!$('#tailSwitch').is(':checked')){
            $('#tail').hide();
        }

        $('#addTags').tagsInput();
        $('#addTags_tag').css("width","100px");


        $('#addMore').on("click",function () {
            var  width=($(window).width()*0.7);
            var height=($(window).height()*0.7);
            layer.open({
                type: 1,
                closeBtn: 0,
                area: [width + 'px', height + 'px'],//大小
                content: $("#addVideo"),
                skin: "layui-layer-molv",
                title:  "新增视频"
                ,btnAlign: 'c'
                ,btn: ['关闭']
                ,yes: function(index, layero){
                    layer.closeAll();
                    location.href =location.href;
                }

            })


        })


        $("#transferBT").click(function () {

            //加载俱乐部下拉框
            $.ajax({
                url:"/sjs/selectAllClub",
                type:"POST",
                success:function(data,status,xhr){
                    var json = eval(data);
                    var html= "<option value=''>请选择俱乐部</option>";

                    $.each(json,function(i,n){

                        html +="<option value='"+n.id+"'>"+n.name+"</option>"
                    });
                    $("#searchClub").append(html)
                    form.render();
                }
            })

            var  width=($(window).width()*0.7);
            var height=($(window).height()*0.7);
            layer.open({
                type: 1,
                closeBtn: 0,
                area: [width + 'px', height + 'px'],//大小
                content: $("#transfer"),
                skin: "layui-layer-molv",
                title:  "迁移视频"
                ,btnAlign: 'c'
                ,btn: ['开始迁移', '取消']
                ,yes: function(index, layero){
                    layero.find('form').find('button[lay-submit]').click();
                    return false
                }
                ,btn2: function(){
                    layer.closeAll();
                    location.href =location.href;
                }
            })

        })
        //排序

        new Sortable(gridDemo, {
            swapThreshold: 1,
            animation: 150,
            store:{

            }
        });

    })

});







